const { FamilyMember, HealthRecord, HealthReminder, HealthReport } = require('../models');

// 获取用户的所有家庭成员
exports.getAllMembers = async (req, res) => {
  try {
    const userId = req.user.id;
    
    const members = await FamilyMember.findAll({
      where: { user_id: userId },
      order: [['createdAt', 'DESC']]
    });
    
    return res.json({
      success: true,
      data: { members }
    });
  } catch (error) {
    console.error('获取家庭成员列表错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 获取单个家庭成员详情
exports.getMemberById = async (req, res) => {
  try {
    const userId = req.user.id;
    const memberId = req.params.id;
    
    const member = await FamilyMember.findOne({
      where: {
        id: memberId,
        user_id: userId
      },
      include: [
        {
          model: HealthRecord,
          as: 'healthRecords',
          limit: 5,
          order: [['record_time', 'DESC']]
        },
        {
          model: HealthReminder,
          as: 'healthReminders',
          limit: 5,
          order: [['remind_time', 'ASC']]
        },
        {
          model: HealthReport,
          as: 'healthReports',
          limit: 5,
          order: [['report_date', 'DESC']]
        }
      ]
    });
    
    if (!member) {
      return res.status(404).json({
        success: false,
        message: '家庭成员不存在'
      });
    }
    
    return res.json({
      success: true,
      data: { member }
    });
  } catch (error) {
    console.error('获取家庭成员详情错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 创建新家庭成员
exports.createMember = async (req, res) => {
  try {
    const userId = req.user.id;
    const { name, avatar, gender, age, birthday, height, weight, blood_type, relationship, medical_history, allergies } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '成员姓名不能为空'
      });
    }
    
    const newMember = await FamilyMember.create({
      user_id: userId,
      name,
      avatar,
      gender,
      age,
      birthday,
      height,
      weight,
      blood_type,
      relationship,
      medical_history,
      allergies,
      health_status: 'normal'
    });
    
    return res.status(201).json({
      success: true,
      data: { member: newMember },
      message: '家庭成员创建成功'
    });
  } catch (error) {
    console.error('创建家庭成员错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 更新家庭成员信息
exports.updateMember = async (req, res) => {
  try {
    const userId = req.user.id;
    const memberId = req.params.id;
    const updateData = req.body;
    
    const member = await FamilyMember.findOne({
      where: {
        id: memberId,
        user_id: userId
      }
    });
    
    if (!member) {
      return res.status(404).json({
        success: false,
        message: '家庭成员不存在'
      });
    }
    
    // 防止修改用户ID
    delete updateData.user_id;
    
    await member.update(updateData);
    
    return res.json({
      success: true,
      data: { member },
      message: '家庭成员信息更新成功'
    });
  } catch (error) {
    console.error('更新家庭成员错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 删除家庭成员
exports.deleteMember = async (req, res) => {
  try {
    const userId = req.user.id;
    const memberId = req.params.id;
    
    const member = await FamilyMember.findOne({
      where: {
        id: memberId,
        user_id: userId
      }
    });
    
    if (!member) {
      return res.status(404).json({
        success: false,
        message: '家庭成员不存在'
      });
    }
    
    await member.destroy();
    
    return res.json({
      success: true,
      message: '家庭成员删除成功'
    });
  } catch (error) {
    console.error('删除家庭成员错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
}; 